package org.luxor.commons.storage.service.impl;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.IOUtils;
import org.luxor.commons.core.utils.IoUtils;
import org.luxor.commons.storage.exception.StorageServiceException;
import org.luxor.commons.storage.service.IThumbImageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 缩略图生成服务
 *
 * @author Mr.Yan  @date 2020/1/2
 */
@Service
public class ThumbImageServiceImpl implements IThumbImageService {
    private static final Logger logger = LoggerFactory.getLogger(ThumbImageServiceImpl.class);

    /**
     * 获取缩略图(自定义大小)
     *
     * @param imageByte 图片内容
     * @param width     缩略图宽度(单位:px像素)
     * @param height    缩略图高度(单位:px像素)
     * @return 缩略图
     * @throws IOException
     */
    @Override
    public byte[] getThumbImage(byte[] imageByte, Integer width, Integer height) throws StorageServiceException {
        ByteArrayInputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
            inputStream = new ByteArrayInputStream(imageByte);
            outputStream = new ByteArrayOutputStream();
            //@formatter:off
            Thumbnails
                    .of(inputStream)
                    .size(width, height)
                    .keepAspectRatio(false)
                    .toOutputStream(outputStream);
            //@formatter:on
            return outputStream.toByteArray();
        } catch (IOException ioe) {
            logger.error("生成缩略图失败!", ioe);
            throw new StorageServiceException("生成缩略图失败!", ioe);
        } finally {
            IoUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(inputStream);
        }
    }
}
